#include <unistd.h>
#include <time.h>
#include "cnats.h"
#include "clog.h"
#include "threads.h"

int recved;

class testWorker:public worker{
private:
    int threadNum;
public:
    testWorker(int num){
        threadNum = num;
    }
    void run(void){
        clog::d("worker:");
        clog::d(threadNum);
        clog::dl("running");
        usleep(rand()%10000);
        clog::d("END: ");
        clog::dl(threadNum);
    }
    void stop(){
        clog::dl("STOP Called");
    }
};

void testForThreads(){
    clog::dl("ThreadTestStart");
    srand((int)time(0));
    threads ths = threads(20);

    for(int i = 0; i < 5; i++){
        ths.addJob(new testWorker(i));
        usleep(rand()%10000);
    }
    ths.stop();
    clog::dl("ThreadTestEnd");
}

class testHandler: public MsgHandler {
private:
    cnats * conn;
    int len;
    char * data;

public:
    testHandler(cnats* conn):
        conn(conn),
        len(1024)
    {
        data = new char[len];
        for (int i = 0; i < len; ++i){
            data[i] = 'a';
        }
    }
    void execute(recvedMsgs *msg){
        recved ++;
        conn->Publish("PONG",data,len);
    }
};

int main(int argc, char const *argv[]){
    clog::setLevel(3);
    clog::il("Start");
    // testForThreads();
    cnats* conn = cnats::Connect("nats://localhost:4222,nats://localhost:4223,nats://localhost:4224");
    conn->Subscribe("PING",new testHandler(conn));
    clog::il("Enter Sleep");
    int lastRecved = recved;
    while(1){
        sleep(1);
        clog::il(recved - lastRecved);
        lastRecved = recved;
    }
    return 0;
}
